package Controler;

import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import View.Checkerboard;


public class CheckerboardListener implements MouseMotionListener, MouseListener,
		KeyListener {
	private Controler controler;
	private Point source;
	private Point dest;
	private boolean moved;
	
	
	public CheckerboardListener(Controler controler){
		this.controler = controler;
		moved = false;
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
		
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getButton() == MouseEvent.BUTTON1){
			if(moved){
				dest = new Point(e.getX(), e.getY());
				dest.setLocation((int)(dest.getX()/Checkerboard.SQUARE_SIZE), (int)(dest.getY()/Checkerboard.SQUARE_SIZE));
				if(!controler.movePiece(source, dest)){
					source = dest;
				}else{
					moved = false;
				}
			}else{
				source = new Point(e.getX(), e.getY());
				source.setLocation((int)(source.getX()/Checkerboard.SQUARE_SIZE), (int)(source.getY()/Checkerboard.SQUARE_SIZE));
				if(controler.selected(source)){
					moved = true;
				}
			}
		}else if(e.getButton() == MouseEvent.BUTTON3){
			moved = false;
			Point selected = new Point(e.getX(),e.getY());
			selected.setLocation((int)(selected.getX()/Checkerboard.SQUARE_SIZE), (int)(selected.getY()/Checkerboard.SQUARE_SIZE));
			if(controler.selected(selected)){
				Point possible = new Point(e.getX(),e.getY());
				possible.setLocation((int)(possible.getX()/Checkerboard.SQUARE_SIZE), (int)(possible.getY()/Checkerboard.SQUARE_SIZE));
				controler.sendPossibleMoves(possible);
				
				source = new Point(e.getX(), e.getY());
				source.setLocation((int)(source.getX()/Checkerboard.SQUARE_SIZE), (int)(source.getY()/Checkerboard.SQUARE_SIZE));
				if(controler.selected(source)){
					moved = true;
				}
			}
		}
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		
	}

	@Override
	public void mouseDragged(MouseEvent arg0) {
		
	}

	@Override
	public void mouseMoved(MouseEvent arg0) {
		
	}

}
